package cn.gzten.lambda.dynamo.sample;

import cn.gzten.lambda.dynamo.sample.data.AppUserDynamoBean;
import cn.gzten.lambda.runtime.util.JsonUtil;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import lombok.extern.slf4j.Slf4j;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;

import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
public class IdentityRequestHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
    private static final DynamoDbClient dynamo = DynamoDbClient.builder()
            .region(Region.AP_EAST_1)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .httpClient(UrlConnectionHttpClient.builder().build())
            .build();

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent param, Context context) {
        var resp = new APIGatewayProxyResponseEvent();
        resp.setStatusCode(200);
        resp.setIsBase64Encoded(false);
        resp.setHeaders(Map.of("Content-Type", "application/json"));

        log.info("Got input: {}", JsonUtil.toJson(param));
        String username;
        if (param.getHttpMethod().equals("POST")) {
            username = ((Map<String, String>)JsonUtil.fromJson(param.getBody(), Map.class)).get("id");
        } else if (param.getHttpMethod().equals("GET")) {
            username = param.getPathParameters().get("id");
        } else {
            String s = String.format("Not supported method: %s", param.getHttpMethod());
            log.info(s);
            resp.setStatusCode(400);
            resp.setBody(s);
            return resp;
        }

        var user = AppUserDynamoBean.getItem(dynamo, username);
        if (user.isPresent()) {
            String body = JsonUtil.toJson(user.get());
            log.info("Got the item from DynamoDB at {} as {}", LocalDateTime.now(), body);
            resp.setBody(body);
        } else {
            String s = String.format("Not found object for id: %s", username);
            resp.setStatusCode(400);
            resp.setBody(s);
        }

        return resp;
    }

}
